package com.lc.pip;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.nio.ByteBuffer;
import java.nio.channels.Pipe;
import java.nio.charset.Charset;

/**
 * @author 逝兮诚
 * @date 2017年6月22日 上午10:01:03
 * @see pipe用做线程之间数据传输，他有SinkChannel和SourceChannel两个内部类
 */
public class Pip3Test {
	public static void main(String[] args) {
		try {
			Pipe pipe = Pipe.open();
			Pipe.SinkChannel sink = pipe.sink();
			Pipe.SourceChannel source = pipe.source();
			Thread threadA = new Thread() {
				public void run() {
					String writeData = "threadA";
					System.out.println("线程A输入数据：" + writeData);
					ByteBuffer byteBuffer = ByteBuffer.allocate(64);
					try {
						byteBuffer.put(writeData.getBytes("UTF-8"));
						byteBuffer.flip();
						while (byteBuffer.hasRemaining()) {
							sink.write(byteBuffer);
						}
						byteBuffer.clear();
						sink.close();
					} catch (UnsupportedEncodingException e) {
						e.printStackTrace();
					} catch (IOException e) {
						e.printStackTrace();
					}
				}
			};
			Thread threadB = new Thread() {
				public void run() {
					ByteBuffer byteBuffer = ByteBuffer.allocate(64);
					try {
						int readSize = source.read(byteBuffer);
						byteBuffer.flip();
						while (readSize != -1) {
							System.out.println(Charset.forName("UTF-8").decode(byteBuffer));
							byteBuffer.clear();
							readSize = source.read(byteBuffer);
						}
						source.close();
					} catch (UnsupportedEncodingException e) {
						e.printStackTrace();
					} catch (IOException e) {
						e.printStackTrace();
					}
				}
			};
			threadA.start();
			threadB.start();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}
